package com.belf.console.agent.migrate.job;

import belf.migrate.engine.admin.taskconf.Job;
import belf.migrate.engine.admin.taskconf.Task;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.belf.common.core.domain.AjaxResult;
import com.belf.common.utils.DateUtils;
import com.belf.console.agent.migrate.BuildTaskConf;
import com.belf.console.agent.migrate.JobPush;
import com.belf.console.domain.DataTaskConf;
import com.belf.console.domain.DataTaskLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * BuildJob
 *
 * @author l
 * @since 2024/7/19 13:43
 */

public class SynJob {

    private static final Logger logger = LoggerFactory.getLogger(SynJob.class.getName());

    public static Job buildJob( DataTaskConf taskData,DataTaskLog jobLog) {
        logger.info("build dataTaskConf:{}", taskData);
        // job 对象
        Job job = new Job();
        job.setJobId(jobLog.getId());
        job.setCreateTime(DateUtils.getNowDate().getTime());
        job.setOwner(jobLog.getCreateBy());
        // 任务对象
        job.setTask(buildTask(taskData));
        String taskTables = taskData.getTaskTables();
        if (taskTables!=null){
            JSONArray parse = JSONArray.parse(taskTables);
            job.setMissions(parse.toList(String.class));
        }

        return job;
    }


    public static Task buildTask(DataTaskConf taskData) {
        Task task = new Task();
        task.setTaskId(taskData.getId());
        task.setName(taskData.getTaskName());
        task.setDesc(taskData.getDsc());
        task.setOwner(taskData.getCreateBy());
        task.setTaskType( taskData.getJobType());
        task.setCreateDate(taskData.getCreateTime().getTime());
        task.setJobMode(taskData.getJobMode());
        task.setTaskPolicy(taskData.getTaskPolicy());
        task.setTaskConf(BuildTaskConf.buildTaskConf(taskData));
        task.setTaskTypeScope(taskData.getTaskTypeScope());
        return task;
    }

    /**
     *  连接引擎获取数据
     * @param APIPath
     * @param task
     * @return
     */
    public static AjaxResult pushJob(String APIPath, DataTaskConf task, DataTaskLog jobLog){
        if(task != null){
            try {
                Job job = buildJob(task,jobLog);
                String jsonString = JSONObject.toJSONString(job);
                    return JobPush.pushTask(APIPath,jsonString);
            } catch (Exception e) {
                logger.error("数据源信息 连接测试失败",e);
            }
        }
        return AjaxResult.error();
    }
}
